package hoang.hut.app.utility;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * NetworkUtility checks available network
 * 
 * @author sonnv6207
 */
public final class NetworkUtility
{
    private Context context = null;
    
    private static NetworkUtility instance = null;
    
    /**
     * Constructor
     * 
     * @param context
     */
    private NetworkUtility(Context context)
    {
        this.context = context;
    }
    /**
     * Get class instance
     * 
     * @param context
     * @return
     */
    public static NetworkUtility getInstance(Context context)
    {
        if (instance == null)
        {
            instance = new NetworkUtility(context);
        }
        return instance;
    }
    
    /**
     * Check network connection
     * 
     * @return
     */
    public boolean isNetworkAvailable()
    {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
        if (i == null)
        {
            return false;
        }
        else if (!i.isConnected()) 
        {
            return false;
        }
        else if (!i.isAvailable()) {
            return false;
        }
        return true;
    }
    /**
     * Checking for all possible internet providers
     * **/
	public static boolean isConnectingToInternet(Context context){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
	
	// Check Internet Connection
	public static boolean isOnline(Context context) {
		ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conMgr.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			return true;
		} else {
			return false;
		}
	}
}
